package com.yihusitian.zsxq.sg.generator;

import cn.hutool.core.util.StrUtil;
import com.yihusitian.zsxq.sg.config.DatasourceInfo;
import com.yihusitian.zsxq.sg.filter.Filter;
import com.yihusitian.zsxq.sg.filter.FilterChain;
import com.yihusitian.zsxq.sg.util.CommonInfoHolder;
import com.yihusitian.zsxq.sg.util.TableMetadataHelper;
import com.yihusitian.zsxq.sg.filter.Filter;
import com.yihusitian.zsxq.sg.filter.FilterChain;
import com.yihusitian.zsxq.sg.util.CommonInfoHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import javax.sql.DataSource;

/**
 * @Description TODO
 * @Author LeeHo
 * @Date 2020/8/26 16:24
 */
public class PreSourceGenerator implements Filter {

    @Override
    public void doFilter(FilterChain filterChain) {
        this.doBeforePostProcessor();
        filterChain.doFilter(filterChain);
    }

    private void doBeforePostProcessor() {
        Assert.notNull(CommonInfoHolder.getCurrentTableInfo().getName(), "当前表名不可为空");
        //设置当前的业务名称
        setCurrentBusinessName();
        //设置当前表对应的所有字段信息
        setFieldListAndTableComment();
    }

    /**
     * 设置当前业务名称
     *
     */
    private void setCurrentBusinessName() {
        String defaultReplacePrefix = CommonInfoHolder.generateConfigHolder.getTables().getDefaultReplacePrefix();
        String currentTableName = CommonInfoHolder.getCurrentTableInfo().getName();
        String tableReplacePrefix = StringUtils.defaultString(CommonInfoHolder.getCurrentTableInfo().getReplacePrefix(), defaultReplacePrefix);
        String businessName = StrUtil.upperFirst(StrUtil.toCamelCase(currentTableName.replace(tableReplacePrefix, StringUtils.EMPTY)));
        CommonInfoHolder.setCurrentBusinessName(businessName);
    }


    /**
     * 设置当前FiledList
     *
     */
    protected void setFieldListAndTableComment() {
        String tableName = CommonInfoHolder.getCurrentTableInfo().getName();
        DatasourceInfo datasourceInfo = CommonInfoHolder.generateConfigHolder.getDatasource();
        String databaseName = CommonInfoHolder.generateConfigHolder.getTables().getDatabase();
        DataSource dataSource = TableMetadataHelper.buildDataSource(datasourceInfo.getJdbcUrl(), datasourceInfo.getUser(), datasourceInfo.getPassword());
        CommonInfoHolder.setCurrentFieldInfoList(TableMetadataHelper.getFieldInfoByDataBaseNameAndTableName(dataSource, databaseName, tableName));
        String tableComment = TableMetadataHelper.getTableComment(dataSource, databaseName, tableName);
        CommonInfoHolder.setCurrentTableComment(StringUtils.isEmpty(tableComment) ? StringUtils.EMPTY : tableComment.replaceAll("表", StringUtils.EMPTY));
    }
}